﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace RAD.LightOne
{
    #region Documentation
    /// <summary>
    /// Atributo base para nomeadores de campos da infraestrutura do framework.
    /// </summary>
    #endregion
    public class FieldNameAttribute:Attribute
    {
        #region Properties

        public KeyField Key
        {
            get;
            protected set;
        }

        public string FieldName
        {
            get;
            protected set;
        }

        #endregion

        #region Constructors

        protected FieldNameAttribute(string fieldName, KeyField key):base()
        {
            if (string.IsNullOrWhiteSpace(fieldName)) throw new ArgumentNullException("fieldName");

            this.FieldName = fieldName;
            this.Key = key;
        }

        #endregion

        #region Methods

        #region Documentation
        /// <summary>
        /// Verifica se o atributo foi atribuido a um membro de classe.
        /// </summary>
        /// <param name="type">tipo a ser analisado.</param>
        /// <returns>Definido=true</returns>
        #endregion
        public static bool IsDefined(Type type)
        {
            return Attribute.IsDefined(type, typeof(FieldNameAttribute));
        }

        protected static bool IsDefined<T>(Type type) where T:FieldNameAttribute
        {
            return Attribute.IsDefined(type, typeof(T));
        }

        public static FieldNameAttribute GetDefinedAttribute(Type type)
        {
            object[] attributes = type.GetCustomAttributes(typeof(FieldNameAttribute), true);
            if (attributes.Length == 0)
            {
                return null;
            }
            else
            {
                return attributes[0] as FieldNameAttribute;
            }

        }

        public static FieldNameAttribute[] GetDefinedAttributes(Type type)
        {
            return (FieldNameAttribute[])type.GetCustomAttributes(typeof(FieldNameAttribute), true);
        }

        protected static T GetDefinedAttribute<T>(Type type) where T: FieldNameAttribute
        {
            object[] attributes = type.GetCustomAttributes(typeof(T), true);
            if (attributes.Length == 0)
            {
                return null;
            }
            else
            {
                return attributes[0] as T;
            }
        }
        #endregion
    }
}
